package com.masc.gurr.model.xml;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;


import com.masc.gurr.model.Contact;
import com.masc.gurr.model.Group;
import com.masc.gurr.model.Message;
import com.masc.gurr.model.ProtocolType;
import com.masc.gurr.model.SessionInfo;

public class Reader {
		
	public Group readContactList(String pStrUin, ProtocolType pProtocolType) {
		
		/** test for protocol type */
		if (pProtocolType.equals(ProtocolType.ICQ)) {
			return readContactListICQ(pStrUin);
		}
		
		
		return null;
	}
	
	/** read sessions:
	 * 
	 * @param pIntStartSid read sessions starting with sid=pIntStartSid, if pIntStartSid==-1 => read from maxid 
	 * @param pIntFollowups number of sessions to read, starting from pIntStartSid.
	 * @return list of messages
	 */
	public List<Message> readHistory(String pStrUin, String pStrBuddy, ProtocolType pProtocolType, int pIntStartSid, int pIntFollowups) {
		List<Message> history = new ArrayList<Message>();
		
		SAXBuilder builder = new SAXBuilder();
		try {
			Document sdoc = builder.build("history.xml");
			Element sroot = sdoc.getRootElement();
			int maxsid=Integer.parseInt(sroot.getAttributeValue("maxsid"));
			
			List schildren = sroot.getChildren();
			Iterator siterator = schildren.iterator();
			
			if (! sroot.getAttributeValue("uin").equals(pStrUin) || ! sroot.getAttributeValue("protocol").equals(pProtocolType.name()) )
				return null;
			
			/** find filename of req. session */
			List<String> sessionFilenames=new ArrayList<String>();
			
			while (siterator.hasNext()) {
				Element session = (Element) siterator.next();
				String sid=session.getAttributeValue("sid");
				int iSid = Integer.parseInt(sid);
				
				String buddy=session.getAttributeValue("buddy");
				System.out.println("sid " + sid + " buddy " + buddy );

				if (buddy.equals(pStrBuddy)) { /** buddy found */
					if (pIntStartSid == -1 && iSid >= (maxsid-pIntFollowups)) { /** start w/ latest session */
							sessionFilenames.add(session.getAttributeValue("file"));
					}
					else if (pIntStartSid > -1 && iSid>=(pIntStartSid-pIntFollowups)) { /** start w/ pIntStartSid and add #pIntFollowups */
							sessionFilenames.add(session.getAttributeValue("file"));
					}
				}
			}

			/** read files an build message-list */
			Iterator<String> itFiles = sessionFilenames.iterator();
			while (itFiles.hasNext()) {
				String file = (String) itFiles.next();
				Document hdoc = builder.build(file);
				Element hroot = hdoc.getRootElement();
				
				if (! hroot.getAttributeValue("buddy").equals(pStrBuddy))
					return null;
				
				List children = hroot.getChildren();
				Iterator it = children.iterator();
				while (it.hasNext()) {
					Element message = (Element) it.next();
					Message msg = new Message(message.getAttributeValue("sender"),
							message.getText(), new Date(Long.parseLong(message.getAttributeValue("date"))));
					history.add(msg);
				}
			}
			return history;
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public SessionInfo readInfo(String pStrUin, ProtocolType pProtocolType) {
		
		SessionInfo s = new SessionInfo(pStrUin, pProtocolType);
		
		SAXBuilder builder = new SAXBuilder();
		try {
			Document doc = builder.build("info.xml");
			Element root = doc.getRootElement();
			
			List children = root.getChildren();
			Iterator iterator = children.iterator();
			
			if (! root.getAttributeValue("uin").equals(pStrUin) || ! root.getAttributeValue("protocol").equals(pProtocolType.name()) )
				return null;
			
			s.setCounter(Integer.parseInt(root.getAttributeValue("counter")));
			
			while (iterator.hasNext()) {
				Element child = (Element) iterator.next();
				System.out.println(child.getName() + " " + child.getAttributeValue("recipient"));
				s.addSid(child.getAttributeValue("recipient"), Integer.parseInt(child.getAttributeValue("sid")));
			}

			return s;
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
		
		return null;
	}
	
	


	/** parse icq contact list and return as group/contact model */ 
	private Group readContactListICQ(String pStrUin) {
		
		Group groupRootElement = new Group("/");
		SAXBuilder builder = new SAXBuilder();
		try {
			Document doc = builder.build("contacts_icq.xml");
			Element root = doc.getRootElement();
			parseContactListICQ(root, groupRootElement);
			return groupRootElement;
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
		
		return null;
	}

	private void parseContactListICQ(Element current, Group group) {
		List children = current.getChildren();
		Iterator iterator = children.iterator();
		if (current.getName().equals("group") ) {
			Group g = new Group(current.getAttributeValue("name"));
			group.addSubGroup(g);
			group = g;
		}
		else if (current.getName().equals("contact") ) {
			Contact c = new Contact(
					current.getAttributeValue("uin"),
					current.getAttributeValue("name"),
					ProtocolType.ICQ,
					current.getAttributeValue("statusmsg"),
					group);
			group.addContact(c);
		}
		
		while (iterator.hasNext()) {
			Element child = (Element) iterator.next();
			parseContactListICQ(child, group);	
		}
	}
}
